package com.zhouyu.paydemo.unipay.qrcode.ZS.ATM;

import com.zhouyu.paydemo.unipay.qrcode.DemoBase;
import com.zhouyu.paydemo.unipay.sdk.QrcService;
import com.zhouyu.paydemo.unipay.sdk.SDKConfig;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用途：取现<br>
 * 日期： 2017-06<br>
 * 声明：以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己需要，按照技术文档编写。该代码仅供参考，不提供编码，性能，规范性等方面的保障<br>
 */
@SuppressWarnings("serial")
@Slf4j
public class CashWithdrawalReversal extends HttpServlet{

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
			String acqCode = req.getParameter("acqCode");
			String txnAmt = req.getParameter("txnAmt");
			String orderNo = req.getParameter("orderNo");
			String orderTime = req.getParameter("orderTime");
			Map<String, String> contentData = new HashMap<String, String>();

			contentData.put("version", "1.0.0");
			contentData.put("reqType", "0560000903");
			contentData.put("acqCode", acqCode);
			contentData.put("orderNo", orderNo);
			contentData.put("orderTime", orderTime);
			contentData.put("txnAmt", txnAmt);
			contentData.put("currencyCode", "156");

			Map<String, String> reqData = QrcService.sign(contentData,DemoBase.encoding);			 //报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
			String requestUrl = SDKConfig.getConfig().getQrcB2cMerBackTransUrl();
			Map<String, String> rspData = QrcService.post(reqData,requestUrl,DemoBase.encoding);  //发送请求报文并接受同步应答（默认连接超时时间30秒，读取返回结果超时时间30秒）;这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过
			
			if(!rspData.isEmpty()){
				if(QrcService.validate(rspData, DemoBase.encoding)){
					log.info("验证签名成功");
					String respCode = rspData.get("respCode") ;
					if(("00").equals(respCode)){

					}else{
						//其他应答码为失败请排查原因
						//TODO
					}
				}else{
					log.error("验证签名失败");
					//TODO 检查验证签名失败的原因
				}
			}else{
				//未返回正确的http状态
				log.error("未获取到返回报文或返回http状态码非200");
			}
			String reqMessage = DemoBase.genHtmlResult(reqData);
			String rspMessage = DemoBase.genHtmlResult(rspData);
			resp.getWriter().write("</br>请求报文:<br/>"+reqMessage+"<br/>" + "应答报文:</br>"+rspMessage+"");
		}
	
}
